<template>
  <el-dialog
    :title="'给分配'+role.auth_key+'角色权限'"
    :visible="dialogVisible"
    :before-close="handleClose"
    :close-on-click-modal="false"
    center
  >
    <el-tree
      v-if="role && role.auth_ids"
      ref="tree"
      v-loading="isLoading > 0"
      :data="auth_list"
      show-checkbox
      default-expand-all
      node-key="id"
      :check-strictly="true"
      highlight-current
      :props=" {
        children: 'children',
        label: 'name_cn'
      }"
    />
    <div class="btn-box">
      <el-button type="primary" size="mini" @click="submitForm()">提交</el-button>
      <el-button size="mini" @click="resetForm()">重置</el-button>
    </div>
  </el-dialog>
</template>

<script>
import lodash from 'lodash'
import { getAllAdminAuthList } from '@/api/admin_auth'
import { transListToTreeData } from '@/utils/tools'
import { updateOneAdminRole } from '@/api/admin_role'
let role_row = null
export default {
  name: 'AdminRoleAddEdit',
  components: {},
  props: {},
  data() {
    return {
      dialogVisible: false,
      isLoading: 0,
      auth_list: [],
      role: {}
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {},
  methods: {
    async getAllAdminAuthList() {
      this.isLoading++
      try {
        let res = await getAllAdminAuthList()
        res = res.filter(item => item.status === 1)
        this.auth_list = transListToTreeData(res)
      } finally {
        this.isLoading--
      }
    },
    handleClose() {
      this.dialogVisible = false
    },
    open(row) {
      this.dialogVisible = true
      role_row = row
      this.getAllAdminAuthList()

      this.resetForm()
    },
    resetForm() {
      this.role = lodash.cloneDeep(role_row)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.role.auth_ids)
      })
    },
    async submitForm() {
      if (this.isLoading > 0) return
      try {
        this.isLoading++
        await updateOneAdminRole({
          id: this.role.id,
          auth_ids: this.$refs.tree.getCheckedKeys()
        })
        this.$emit('refresh')
        this.handleClose()
      } finally {
        this.isLoading--
      }
    }

  }
}
</script>

<style lang="scss" scoped>
.submit-box {
  display: flex;
  justify-content: flex-end;
}
.btn-box {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
